<template>
  <div class="cateManage">
    <a-button type="primary" class="addbtn" @click="showAdd">新增</a-button>
    <a-table
      :columns="columns"
      :data-source="cates"
      :loading="loading"
      :row-key="(record:Cate)=>record.id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <a-button type="primary" class="editbtn" @click="showEdit(record)"
            >编辑</a-button
          >
          <a-space size="small">
            <a-popconfirm
              title="确定删除该书籍？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="confirm($event, record.id)"
            >
              <a-button type="primary" danger> 删除 </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- modal -->
    <a-modal v-model:visible="visible" :title="modalTitle" @ok="handleEdit_Add">
      <a-form
        :model="formState"
        name="basic"
        :rules="rules"
        :labelCol="{ span: 4 }"
        autocomplete="off"
      >
        <a-form-item label="名称" name="name">
          <a-input v-model:value="formState.name" />
        </a-form-item>
        <a-form-item label="父分类" name="parent">
          <a-select
            ref="select"
            v-model:value="formState.parent"
            @change="handleChange"
          >
            <a-select-option
              v-for="item in level1"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              :disabled="item.id === formState.id"
              >{{ item.name }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item label="顺序" name="sort">
          <a-input v-model:value="formState.sort" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { getCategoryAllList, removeCate, editCate } from "@/api/cate";
import { toTree, getLevel1 } from "@/util/toTree";
import { Form, message } from "ant-design-vue";
import type { CascaderProps } from "ant-design-vue";

const useForm = Form.useForm;
let loading = ref(true);
const columns = [
  { title: "名称", dataIndex: "name", key: "name" },
  { title: "父分类", dataIndex: "parent", key: "parent" },
  { title: "顺序", dataIndex: "sort", key: "sort" },
  { title: "Action", key: "action" },
];
interface Cate {
  id: number;
  name: string;
  parent: number;
  sort: number;
}
const cates = reactive<Cate[]>([
  // {
  //  id: number;
  // name: string;
  // parent: number;
  // sort: number;
  // children?: Cate[];
  // },
]);
const level1: CascaderProps["options"] = [];

// 请求数据（递归tree）
const handleQuery = () => {
  loading.value = true;
  getCategoryAllList().then((res) => {
    // console.log(res);

    loading.value = false;
    // 分类数据
    cates.length = 0;
    let cateTree = toTree(res.data.data);
    cates.push(...cateTree);
    //
    level1.length = 0;
    level1?.push(...getLevel1(res.data.data));

    // console.log(cates);
  });
};

onMounted(() => {
  handleQuery();
});

// 表单
const modalTitle = ref<string>("");
const visible = ref<boolean>(false);
let formState = reactive<any>({
  id: 0,
  name: "",
  parent: 0,
  sort: 0,
});
const rules = reactive({
  name: [{ required: true, message: "不为空", trigger: "blur" }],
  parent: [{ required: true, message: "不为空", trigger: "blur" }],
  sort: [{ required: true, message: "不为空", trigger: "blur" }],
});
// 验证
const { resetFields, validate, validateInfos } = useForm(formState, rules);

// ======================= 删除
const confirm = (e: MouseEvent, id: number) => {
  // 删除请求
  removeCate(id).then((res) => {
    if (res.data.code == 10001) {
      message.success("删除成功");

      // 刷新页面
      handleQuery();
    } else {
      message.error("删除失败,请稍后重试");
    }
  });
};

//  ===================== 显示修改
const showEdit = (record: any) => {
  modalTitle.value = "类别编辑";
  visible.value = true;
  // 赋值
  for (let key in formState) {
    formState[key] = record[key];
  }
};
// ===================== 修改下拉菜单的数值
const handleChange = (value: number) => {
  formState.parent = value;
};
// ===================== 显示添加
const showAdd = (record: any) => {
  modalTitle.value = "添加类别";
  visible.value = true;
  //
  resetFields();
};

//  ========================== 增加 / 修改 ==========================
const handleEdit_Add = () => {
  validate().then((res) => {
    // 修改
    editCate(formState).then((res) => {
      // console.log(res);

      if (res.data.code === 10001) {
        message.success("修改成功");
        // 刷新页面
        handleQuery();
        visible.value = false;
        return;
      }
      message.error("修改失败,请稍后重试");
    });
  });
};
</script>
<style scoped>
.cateManage {
  padding: 20px;
}
.addbtn {
  margin-bottom: 10px;
}
.editbtn {
  margin-right: 10px;
}
</style>
